//
//  UIViewController+Menu.m
//  YDGJ
//
//  Created by ydcq on 16/7/14.
//  Copyright © 2016年 Galaxy360. All rights reserved.
//

#import "UIViewController+Menu.h"
#import <objc/runtime.h>

static void *storageBlockKey = "storageBlockKey";

@implementation UIViewController (Menu)

- (void)showMenuWithTitles:(NSArray *)titles  selectBlock:(void(^)(NSInteger))blk
{
    objc_setAssociatedObject(self, storageBlockKey, blk, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    UIMenuController *popMenu = [UIMenuController sharedMenuController];
    UIMenuItem *item1 = [[UIMenuItem alloc] initWithTitle:@"出库" action:@selector(storageOut)];
    UIMenuItem *item2 = [[UIMenuItem alloc] initWithTitle:@"入库" action:@selector(storageIn)];
    [popMenu setMenuItems:@[item1,item2]];
    [popMenu setArrowDirection:UIMenuControllerArrowDown];
    [popMenu setTargetRect:CGRectMake(Screen_Width/3.f, Screen_Height-kDefaultCellHeight, Screen_Width/3.f, kDefaultCellHeight) inView:self.view];
    [popMenu setMenuVisible:YES animated:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuDidHide) name:UIMenuControllerDidHideMenuNotification object:nil];
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(storageIn) || action == @selector(storageOut)) {
        return YES;
    }
    return NO;
}

- (void)storageIn
{
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    void (^blk)(NSInteger) = objc_getAssociatedObject(self, storageBlockKey);
    if (blk) {
        blk(1);
    }
}

- (void)storageOut
{
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    void (^blk)(NSInteger) = objc_getAssociatedObject(self, storageBlockKey);
    if (blk) {
        blk(0);
    }
}

- (void)menuDidHide
{
    [[UIMenuController sharedMenuController] setMenuItems:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIMenuControllerDidHideMenuNotification object:nil];
}

@end
